package javaVersion.learn.batchProcess;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Pro7_BroadCast {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        ArrayList<Tuple2<String,Integer>> broadData  = new ArrayList<>();
        broadData.add(new Tuple2<>("zs",18));
        broadData.add(new Tuple2<>("ls",20));
        broadData.add(new Tuple2<>("ww",17));
        DataSource<Tuple2<String, Integer>> dataSource = env.fromCollection(broadData);
        MapOperator<Tuple2<String, Integer>, HashMap<String, Integer>> toBroadcast = dataSource.map(new MapFunction<Tuple2<String, Integer>, HashMap<String, Integer>>() {
            @Override
            public HashMap<String, Integer> map(Tuple2<String, Integer> value) {
                HashMap<String, Integer> result = new HashMap<>();
                result.put(value.f0, value.f1);
                return result;
            }
        });

        //编写元数据
        DataSource<String> data = env.fromElements("zs", "ls", "ww");
        
        //使用RichMapFunction获取广播变量
        MapOperator<String, String> getBroadCast = data.map(new RichMapFunction<String, String>() {
            List<HashMap<String, Integer>> broadCastMap = new ArrayList<>();
            HashMap<String, Integer> map = new HashMap<>();

            @Override
            public void open(Configuration parameters) throws Exception {
                //生命周期方法中，open方法只会执行一次
                super.open(parameters);
                //获取广播数据
                this.broadCastMap = getRuntimeContext().getBroadcastVariable("broadCastMapName");
                for (HashMap<String, Integer> integerHashMap : broadCastMap) {
                    map.putAll(integerHashMap);
                }
            }

            @Override
            public String map(String value) {
                Integer integer = map.get(value);
                return value + "," + integer;
            }
            //执行广播数据
        }).withBroadcastSet(toBroadcast,"broadCastMapName");
        getBroadCast.print();
    }
}
